<template>
  <div class="full-box d-flex-c overflow-hidden">
    <div class="full-width half-height-panel d-flex-c m-b-s ">
      <div
        class="panel-title-bg flex-between flex-0"
      >
        <div
          class="flex-ai-c panel-title"
          :class="{'active':visibleLayerId===swswLayerId}"
          @click="changeLayerVisible(swswLayerId)"
        >
          <i class="ri-map-pin-5-fill  m-r-7 f-20" />
          <div class="panel-title-text flex-ai-c flex-0 m-r-s ">
            水文水位站<span>({{ swTotal }})</span>
          </div>
        </div>

        <div class="flex-ai-c">
          <BKSelect
            v-model="searchForm.STTP"
            placeholder="站类"
            size="mini"
            clearable
            :mock="stationTypeList"
            class="blue-select m-r-mini"
            popper-class="blue-select-dropdown"
          />
          <BKSelect
            v-model="searchForm.BSNM"
            placeholder="流域分区"
            size="mini"
            clearable
            :mock="watershedZones"
            class="blue-select m-r-mini"
            popper-class="blue-select-dropdown"
          />
          <el-cascader
            v-model="searchForm.ADDVCD"
            class="blue-select"
            placeholder="行政区域"
            :options="adminAreas"
            popper-class="blue-select-dropdown"
            :props="{ checkStrictly: true }"
            :show-all-levels="false"
            filterable
            clearable
          />
        </div>
      </div>
      <div class="d-flex-c panel-box-outline full-width">
        <div class="flex-1 panel-table">
          <ConfigGrid
            ref="swGrid"
            class="ysqxx-table"
            border="none"
            :stripe="false"
            :has-seq="false"
            :has-toolbar-left="false"
            :highlight-current-row="true"
            :has-pager="false"
            :has-add="false"
            :has-batch-remove="false"
            :has-checkbox="false"
            :toolbar-config="null"
            :configs="swConfigs"
            :after-query="swAfterQuery"
            @scroll="handleScroll"
            @current-change="({row})=>currentChange(row,swswLayerId)"
          />
        </div>
        <div class="flex-0 overflow-hidden panel-chart">
          <BKChart
            :option="swswOption"
            @click="(data)=>handleSwClickChart(data,swswLayerId)"
          />
          <!-- <el-empty
            v-show="!swswOption"
            :image-size="80"
            class="full-box m-a-s"
          /> -->
        </div>
      </div>
    </div>
    <div class="full-width d-flex-c half-height-panel">
      <div
        class="panel-title-bg flex-between flex-0"
      >
        <div
          class="flex-ai-c panel-title"
          :class="{'active':visibleLayerId===szLayerId}"
          @click="changeLayerVisible(szLayerId)"
        >
          <i class="ri-map-pin-5-fill  m-r-7 f-20" />
          <div class="panel-title-text flex-0">
            水质站<span>({{ szTotal }})</span>
          </div>
        </div>

        <div class="flex-ai-c">
          <el-date-picker
            class="blue-select blue-date-picker"
            popper-class="blue-select-dropdown"
            v-model="month"
            type="month"
            size="mini"
            prefix-icon=""
            :picker-options="pickerOptions"
            :clearable="false"
            placeholder="选择年月"
          />
        </div>
      </div>
      <div class="d-flex-c panel-box-outline full-width">
        <div class="flex-1 panel-table">
          <!-- <ScrollTable  class="ysqxx-table"></ScrollTable> -->
          <ConfigGrid
            ref="szGrid"
            class="ysqxx-table"
            border="none"
            :stripe="false"
            :has-seq="false"
            :has-toolbar-left="false"
            :highlight-current-row="true"
            :has-pager="false"
            :has-add="false"
            :has-batch-remove="false"
            :has-checkbox="false"
            :toolbar-config="null"
            :configs="szConfigs"
            :after-query="szAfterQuery"
            @current-change="({row})=>currentChange(row,szLayerId)"
          />
        </div>
        <div class="flex-0 overflow-hidden panel-chart">
          <BKChart
            :option="szOption"
            @click="(data)=>handleSwClickChart(data,szLayerId)"
          />
        </div>
      </div>
    </div>
    <SwswModal
      ref="swswModal"
    />
  </div>
</template>
<script>
import { mapState } from 'vuex'
import { getBarOption, maxBarWidth } from '@/components/chart/echart-utils'
import { nextTick } from '@vue/composition-api'
import { szLayerId, swswLayerId } from '../../variable'
import SwswModal from '../../components/business/swsw-modal.vue'
// import ScrollTable from '@/components/scroll-table'
export default {
  name: 'YsqxxStationLeft',
  components: { SwswModal },
  data () {
    return {
      searchForm: {
        STTP: '',
        ADDVCD: ['130000'],
        BSNM: ''
      },
      swswOption: null,
      szOption: null,
      month: '2024-03-01',
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      pageSize: 50,
      swPageNum: 1,
      szPageNum: 1,
      swTotal: 0,
      szTotal: 0,
      swConfigs: {
        isView: false,
        noOperation: true,
        noParentParam: true,
        appId: 'YSJC',
        bzCode: 'YSJC',
        metaSet: 'YSQJC_ST_STBPRP_B',
        gridMethod: 'SWSW_GetList',
        defaultQueryParamsProcessor: this.swDefaultQueryParamsProcessor
      },
      szConfigs: {
        isView: false,
        noOperation: true,
        noParentParam: true,
        appId: 'YSJC',
        bzCode: 'YSJC',
        metaSet: 'YSQJC_WQ_WATER_QUALITY',
        gridMethod: 'SZ_getAllList',
        defaultQueryParamsProcessor: this.szDefaultQueryParamsProcessor
      },
      szLayerId: szLayerId,
      swswLayerId: swswLayerId
    }
  },

  computed: {
    ...mapState('ysqxx', ['adminAreas', 'stationTypeList', 'watershedZones', 'visibleLayerMap', 'visibleLayerId']),
    swswLayerVisible () {
      return this.visibleLayerMap[this.swswLayerId]
    },
    szLayerVisible () {
      return this.visibleLayerMap[this.szLayerId]
    }
  },
  watch: {
    searchForm: {
      deep: true,
      immerate: false,
      handler (v) {
        this.$store.commit('ysqxx/setMapStationQueryParam', {
          SWADDVCD: v.ADDVCD.length ? v.ADDVCD[v.ADDVCD.length - 1] : '130000',
          SWBSNM: v.BSNM,
          STTP: v.STTP
        })
        this.$root.$emit('mapStationPointSearch')
        nextTick(async () => {
          this.$refs.swGrid.refreshList()
          await this.setSwswOption()
        })
      }
    },
    month: {
      immediate: false,
      handler (v) {
        this.$store.commit('ysqxx/setMapStationQueryParam', {
          SEARCH_TIME: this.$utils.formatDate(v, 'YYYY-MM-DD')
        })
        this.$root.$emit('mapStationPointSearch')
        nextTick(async () => {
          this.$refs.szGrid.refreshList({ SEARCH_TIME: this.$utils.formatDate(this.month, 'YYYY-MM-DD') })
          await this.setSzOption()
        })
      }
    }
  },
  created () {
    this.$root.$on('clearOtherActiveRow', this.clearOtherActiveRow)
  },
  mounted () {
    this.$refs.swGrid.refreshList()
    this.$refs.szGrid.refreshList({ SEARCH_TIME: this.$utils.formatDate(this.month, 'YYYY-MM-DD') })
    this.setSwswOption()
    this.setSzOption()
  },
  beforeDestroy () {
    this.$root.$off('clearOtherActiveRow', this.clearOtherActiveRow)
  },
  methods: {
    swDefaultQueryParamsProcessor (params) {
      params.pageNum = this.szPageNum
      params.pageSize = this.pageSize
      const tempMethodParams = JSON.parse(params.methodParams)
      const filterParam = {}
      tempMethodParams.columnFilterParam.forEach(ele => {
        filterParam[ele.field] = ele.conditions[0].value ? ele.conditions[0].value : ele.conditions[1].value
      })
      const methodParams = {
        BSNM: this.searchForm.BSNM,
        STTP: this.searchForm.STTP,
        ADDVCD: this.searchForm.ADDVCD.length ? this.searchForm.ADDVCD[this.searchForm.ADDVCD.length - 1] : '130000',
        ...filterParam
      }
      params.methodParams = JSON.stringify(methodParams)
      console.log({ methodParams, tempMethodParams })
      return params
    },
    szDefaultQueryParamsProcessor (params) {
      params.pageNum = this.szPageNum
      params.pageSize = this.pageSize
      const tempMethodParams = JSON.parse(params.methodParams)
      const filterParam = {}
      tempMethodParams.columnFilterParam.forEach(ele => {
        filterParam[ele.field] = ele.conditions[0].value ? ele.conditions[0].value : ele.conditions[1].value
      })
      const methodParams = {
        SEARCH_TIME: this.$utils.formatDate(this.month, 'YYYY-MM-DD'),
        ...filterParam
      }
      params.methodParams = JSON.stringify(methodParams)
      return params
    },
    swAfterQuery (params) {
      this.swTotal = params.total
      return params.rows
    },
    szAfterQuery (params) {
      this.szTotal = params.total
      // const data = params.rows.map(item => {
      //   // console.log({ WATER_QUALITY_ADDRESS: item.WATER_QUALITY_ADDRESS.match(new RegExp(`${item.CITY_CODE_TEXT}(\\S*)`))[1] })
      //   return {
      //     ...item
      //   }
      // })
      return params.rows
    },
    async setSwswOption () {
      console.log({ form: this.searchForm })
      const { data } = await this.$request.post('ysjc/jsc/selectStationCount', {
        BSNM: this.searchForm.BSNM,
        STTP: this.searchForm.STTP,
        // 默认河北省
        ADDVCD: this.searchForm.ADDVCD.length ? this.searchForm.ADDVCD[this.searchForm.ADDVCD.length - 1] : '130000',
        STCD_TYPE: 'SW'
      })
      // if (!data.length) {
      //   this.swswOption = null
      //   return
      // }
      const result = getBarOption({
        yAxisName: '个',
        xAxis: data.map(r => r.xzqmc),
        series: [
          {
            name: '总数',
            type: 'bar',
            color: ['#18395d00', '#047DF3'],
            data: data.map(r => {
              return {
                ...r,
                value: r.num
              }
            })
          }
        ]
      })
      if (!data.length) {
        result.grid.left = 20
      }
      result.grid.bottom = 0
      result.series[0].itemStyle.borderRadius = [maxBarWidth, maxBarWidth, 0, 0]
      result.series[0].label = {
        show: true,
        position: 'top',
        fontSize: '14px',
        color: '#fff'
      }
      result.xAxis.axisLabel.color = '#C4CBD9'
      result.yAxis.axisLabel.color = '#C4CBD9'
      result.xAxis.axisLine = {
        show: true,
        lineStyle: {
          color: 'rgba(233,237,240,0.1)'
        }
      }
      result.xAxis.axisLabel.rotate = 40
      result.xAxis.axisLabel.interval = 0
      result.yAxis.splitLine.show = false
      result.yAxis.axisLine = {
        show: true,
        lineStyle: {
          color: 'rgba(233,237,240,0.1)'
        }
      }
      result.yAxis.nameTextStyle = {
        color: '#C4CBD9',
        fontSize: '14px',
        padding: [0, 0, 0, -20]
      }
      result.tooltip.appendToBody = true
      this.swswOption = result
    },
    async setSzOption () {
      const { rows } = await this.$request.singleTableOperation({
        url: '/grid/getTableData',
        metaSet: 'YSQJC_WQ_WATER_QUALITY',
        methodCode: 'SZ_getTjList',
        methodParams: JSON.stringify({
          queryParam: {
            SEARCH_TIME: this.$utils.formatDate(this.month, 'YYYY-MM-DD')
          }
        })
      })

      const result = getBarOption({
        yAxisName: '个',
        hasLegend: true,
        xAxis: rows.map(r => r.NAME),
        series: [
          {
            name: '当前日期',
            type: 'bar',
            color: ['#18395d00', '#047DF3'],
            data: rows.map(r => {
              return {
                ...r,
                value: r.NOW_DATA_NUM
              }
            })
          },
          {
            name: '去年同期',
            type: 'bar',
            color: ['#18395d00', '#07FFDE'],
            data: rows.map(r => {
              return {
                ...r,
                value: r.LAST_YEAR_NUM
              }
            })
          }
        ]
      })
      if (!rows.length) {
        result.grid.left = 20
      }
      result.series = result.series.map((s) => {
        return {
          ...s,
          barMaxWidth: 10,
          itemStyle: {
            ...s.itemStyle,
            borderRadius: [maxBarWidth, maxBarWidth, 0, 0]
          }
        }
      })

      result.xAxis.axisLabel.color = '#C4CBD9'
      result.yAxis.axisLabel.color = '#C4CBD9'
      result.xAxis.axisLine = {
        show: true,
        lineStyle: {
          color: 'rgba(233,237,240,0.1)'
        }
      }
      result.yAxis.splitLine.show = false
      result.yAxis.axisLine = {
        show: true,
        lineStyle: {
          color: 'rgba(233,237,240,0.1)'
        }
      }
      result.yAxis.nameTextStyle = {
        color: '#C4CBD9',
        fontSize: '14px',
        padding: [0, 0, 0, -20]
      }
      result.legend = {
        ...result.legend,
        textStyle: {
          color: '#FFFFFF'
        }
      }
      result.tooltip.appendToBody = true
      this.szOption = result
    },
    handleSwClickChart (data, type) {
      nextTick(() => {
        this.$refs.swswModal.openModal({
          chartData: data.data,
          params: type === this.szLayerId ? {
            SFNOW: data.seriesName === '去年同期' ? 'LAST' : 'NOW',
            SZLB: data.data.ITEMCODE,
            SEARCH_TIME: this.month
          } : {
            ...this.searchForm
          },
          layId: type
        })
      })
    },
    handleScroll ({ scrollTop, scrollHeight, bodyHeight, $event }) {
      // console.log({ scrollTop, scrollHeight, bodyHeight, $event })
    },
    async currentChange (row, layerId) {
      console.log({ row })
      this.$root.$emit('selectTableStation', { coordinate: [row.LGTD, row.LTTD], row, layerId })
    },
    changeLayerVisible (layId) {
      const visible = this.visibleLayerId !== layId
      this.visibleLayerId === layId ? this.$store.commit('ysqxx/setVisibleLayerId', '') : this.$store.commit('ysqxx/setVisibleLayerId', layId)
      this.$emit('changeLayerVisible', layId, visible)
    },
    clearOtherActiveRow (layerId) {
      nextTick(() => {
        if (layerId !== this.szLayerId) {
          this.$refs.szGrid.$children[0].clearCurrentRow()
        }
        if (layerId !== this.swswLayerId) {
          this.$refs.swGrid.$children[0].clearCurrentRow()
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.blue-select.blue-date-picker {
  width: 120px !important;
}

</style>
